<template>
<div class="login">
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="name">
    <el-input v-model="ruleForm.name"></el-input>
  </el-form-item>

  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="ruleForm.password"></el-input>
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
    <el-button @click="resetForm('ruleForm')">注册</el-button>
  </el-form-item>
</el-form>
</div>
</template>

<script>
export default {
   data() {
      return {
        ruleForm: {
          name: 'admin',
          password: '123456'
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:[
            {required:true,message:'请输入密码',trigger:'blur'}
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let {name,password}=this.ruleForm;
            this.$http({
              method:'post',
              url:'get_login',
              data:{user:name,password:password}
            }).then(res=>{
              if(res.status==200){
                sessionStorage.setItem('username',name)
                sessionStorage.setItem('password',password)
                this.$router.push('/home')
                this.$message.success('登录成功')
              }else{
                sessionStorage.setItem('username',name)
                sessionStorage.setItem('password',password)
                this.$router.push('/home')
                this.$message.success('登录成功')
              }
            }).catch(res=>{
              if(res.status==404){
                this.$message.error('后端服务错误')
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
}
</script>